﻿using System;
using System.Collections.Generic;
using EHR18.Models;
using System.Threading;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;

using System.Threading.Tasks;
using Common;
using EHR18.Models;


namespace EHR18
{
    public enum CELL_MODE { NORMAL = 0, STOPING };
    public class ProductMachine
    {
        I_IO_Card instance =IOFactory.getIO_Instance(GenneralConfig.instance.IO_TYPE);
        ModuleConfig g_module = GenneralConfig.instance.module;
       public  Queue<Product> Products = new Queue<Product>();
        List<TestSpan> spans = new List<TestSpan>();
        public CELL_MODE cellMode = CELL_MODE.NORMAL;
        public Action<string> ShowMsg;
        public event Action<List<TestSpan>> ShowTestSpan;
        public static object objLock = new object();
        public string ModelName { get; set; }
        public object loker = new object();
        public List<TestItem> TestItems
        {
            get { return GenneralConfig.instance.module.TestItems; }
        }
        public string className { get { return GenneralConfig.instance.module.ClassName; } set { GenneralConfig.instance.module.ClassName = value; }}
        public int totalFail { get; set; }
        ProductMachine()
        {
            try
            {
               instance.TrigEvent += instance_TrigEvent;
            }
            catch (Exception)
            {
            }
        }
        public static readonly ProductMachine inst=new ProductMachine();
        void instance_TrigEvent(ushort TrigValue)
        {
         //  var q = g_module.TestItems.Where(t=>t.Name.Contains("漏感"));
            if ((TrigValue&(1 <<g_module.DI_TEST_OVER))>0)
            {               
                Step();
                instance.tag = 0;
            }
        }
 
        // 步进测试容器中的所有产品
        public void Step()
        {
            lock (loker)
            {
                spans.Clear();
                if (cellMode == CELL_MODE.NORMAL)
                {
                    Product pd = ProductFactory.CreateProduct(GenneralConfig.instance.module.ClassName);
                    pd.ModelName = ModelName;
                    pd.ShowMsg = ShowMessage;
                    pd.ShowTestSpan = _ShowTestSpan;
                    Products.Enqueue(pd);

                }
                if (Products.Count> TestItems.Count||(cellMode==CELL_MODE.STOPING))
                {
                    if (Products.Count >= 1)
                    {
                        Product pd = Products.Dequeue();
                        Task ts = Task.Factory.StartNew(pd.InsertTable);
                        if (pd.B_Fail)
                        {
                            CountManager.AddFail("总体结果");
                      //      ShowMsg("[总体结果]失败");
                        }
                        else
                        {
                            CountManager.AddPass("总体结果");
                      //       ShowMsg("[总体结果]成功");
                        }
                    }
                    else
                    {
                       ShowMessage("[错误]：[没有可用对象]");
                    }
                }
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                instance.WriteBit(g_module.DO_READ_OK, false);
                foreach (Product pd in Products)
                {
                    TestProduct(pd);                  
                }

                
                instance.WriteBit(g_module.DO_READ_OK, true);
                sw.Stop();
                LogHelper.WriteLog(typeof(Product), string.Format("数据采集完成,总用时[{0}]ms", sw.ElapsedMilliseconds));
                spans.Reverse();
                List<TestSpan> spans_copy = CommonHelper.Clone(spans);
                ShowTestSpan(spans_copy);
                if (instance.ReadBit((uint)g_module.DI_FINNISH_MODE))
                {
                    ShowMessage("[停止模式]");
                    cellMode = CELL_MODE.STOPING;
                }
                else
                {
                    ShowMessage("[正常模式]");
                    cellMode = CELL_MODE.NORMAL;
                }              
            }
        }
        private void TestProduct(object _pd)
        {
            lock (objLock)
            {
                Product pd = _pd as Product;
                if (pd.Test() < 0)
                {
                    totalFail++;
                }
                pd.StepLocation();
            }
        }

        public void _ShowTestSpan(List<TestSpan> testspans)
        {
            spans.AddRange(testspans);
        }

        public void ClearProducts()
        {
            Products.Clear();
        }
        void ShowMessage(string Msg)
        {
            LogHelper.WriteLog(typeof(ProductMachine), Msg);
        }
    }

}
